(function () {
    "use strict";

    var app = angular.module('app');

    app.controller('wct.menu', WctMenuCtrl);

    WctMenuCtrl.$inject = [
        '$scope',
        'A',
        '$win',
        '$dialog',
        '$toast',
        'Api',
        'WctMenuService'
    ];

    function WctMenuCtrl($scope, A, $win, $dialog, $toast, Api, WctMenuService) {
        $scope.progress = A.PromiseTracker();
        // $scope.wxButtonTree = {};

        $scope.options = {
            api       : Api.wct.menu.get,
            dataIndex : 'buttons',
            childIndex: 'subButtons',
            // isLeaf : function(row) {
            // if (row.subButtons.length === 0) {
            // return true;
            // }
            // return false;
            // },
            column    : [
                {
                    text : '按钮名',
                    name : 'name',
                    ratio: 2,
                    tree : true
                },
                {
                    text: '类型',
                    name: 'type'
                },
                {
                    text : '链接',
                    name : 'url',
                    ratio: 4
                },
                {
                    text: 'key',
                    name: 'key'
                },
                {
                    text : '操作列',
                    items: [

                        {
                            icon   : 'fa fa-plus',
                            tooltip: '添加下级菜单',
                            disable: function (row) {
                                if (row.level == 1) {
                                    return false;
                                }

                                return true;
                            },
                            handler: function (o, row) {
                                createMenu(row);
                            }
                        },
                        {
                            icon   : 'fa fa-pencil-square-o',
                            tooltip: '修改',
                            handler: function (o, row) {
                                // updateMenu(row.ik);
                                // row.name = '实时修改效果';
                                console.log(o, row);

                                //var newMenu = $scope.wxButtonTree.getTreeData();

                                showDialog();
                            }
                        },
                        {
                            icon   : 'fa fa-remove',
                            tooltip: '删除',
                            handler: function (o, row) {
                                var msg = "确认删除？";
                                if (row.subButtons.length > 0) {
                                    msg = '确认删除当前及其下级菜单?';

                                }
                                $dialog.confirm(msg, function (confirm) {
                                    if (confirm) {

                                        /*		 获取所有菜单
                                         获取行菜单
                                         把一级菜单和所选的菜单进行遍历
                                         如果一级菜单下没有子菜单就直接删除
                                         如果一级菜单下有子菜单，就直接删除该菜单下的所有子菜单再删除该一级菜单
                                         如果是二级菜单，就把该一级菜单下的子菜单进行遍历，找到则删除

                                         前端效果 如果后台未删除，前端还是会立即删除，该问题用下面的方法会删除失败
                                         菜单循环添加 组合成一个新菜单传入后台
                                         */
                                        // var wctMenu =
                                        // angular.merge({},$scope.wxButtonTree.getTreeData());
                                        var wctMenu = $scope.wxButtonTree.getTreeData();
                                        //

                                        var menu = row;
                                        // 遍历一级菜单
                                        for (var i = 0; i < wctMenu.length; i++) {
                                            // 如果一级菜单的某一项等于我所选中的一行的值
                                            if (menu.level == 1) {
                                                if (menu.name == wctMenu[i].name && menu.type == wctMenu[i].type) {

                                                    // 一级菜单

                                                    // 是否有二级菜单单
                                                    if (menu.subButtons.length == 0) {
                                                        // 否
                                                        wctMenu.splice(i, 1);
                                                        break;
                                                    } else {
                                                        // 删除所有菜单(先删子集)

                                                        menu.subButtons.splice(0, menu.subButtons.length);
                                                        wctMenu.splice(i, 1);
                                                        break;
                                                    }
                                                }

                                            } else {
                                                // 遍历的二级菜单
                                                for (var j = 0; j < wctMenu[i].subButtons.length; j++) {
                                                    if (wctMenu[i].subButtons[j].name == menu.name && wctMenu[i].subButtons[j].type == menu.type) {

                                                        wctMenu[i].subButtons.splice(j, 1);
                                                        if (wctMenu[i].subButtons.length == 0) {

                                                            wctMenu.splice(i, 1);
                                                        }
                                                        break;
                                                    }
                                                }

                                            }
                                        }
                                        deleteMenu(wctMenu);
                                    }

                                });

                            }
                        }
                    ]
                }
            ]
        };

        var deleteMenu = function (wctMenu) {
            console.log($scope.wctMenu);
            WctMenuService.remove(wctMenu).then(function (result) {
                if (result.success) {
                    $toast.success("删除成功！");
                    $scope.wxButtonTree.reload();
                } else {
                    $toast.warn(result.msg || "删除失败！");
                }
            })
        };

        // 调用创建方法
        var canCreateByRow = function (row) {
            var wctMenus = $scope.wxButtonTree.getTreeData() || [];
            if (!row) { // 一级菜单时
                return wctMenus.length < 3;
            }
            // 二级菜单时
            var result = true;
            angular.forEach(wctMenus, function (i, item) {
                if (item.name === row.name) { // todo 是不是用 name 判断
                    result = item.subButtons.length < 5;
                }
            });
            return result;
        };
        var createMenu = function (row) {
            // 验证菜单 1 自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
            // 2、一级菜单最多4个汉字，二级菜单最多7个汉字，多出来的部分将会以“...”代替
            if (!canCreateByRow(row)) {
                $toast.warn('一级菜单最多添加3个菜单, 二级菜单最多添加5个菜单.');
                return; // return 掉之后的代码就不会执行了
            }
            $scope.parentNode = row;
            console.log("================的值" + $scope.parentNode);
            showDialog();
        };

        var wctMenuDialog;
        var showDialog = function () {
            wctMenuDialog = $win.open({
                template: 'wctMenuDialog',
                scope   : $scope
            });

        };

        $scope.wctMenu = {};

        $scope.create = function () {
            $scope.wctMenu = {
                type: 'view'
            }; // 创建时重置 wctMenu 对象
            createMenu();
        };

        $scope.warn = function () {
            Swal.warn($scope.msg);
        };

        $scope.submit = function () {
            var oldMneu = $scope.wxButtonTree.getTreeData();

            // console.log("添加的對象=" + $scope.wctMenu);
            if ($scope.parentNode != null) {
                // 是二級菜單
                // console.log("二級菜單加進去=" +
                $scope.parentNode.subButtons.push($scope.wctMenu);
                console.log($scope.parentNode);
                angular.forEach($scope.parentNode, function (i, item) {
                    console.log(i + "=行对象=" + item);
                })
                $scope.wxButtonTree.getTreeData().push($scope.parentNode);
//				console.log("=！！！=" + $scope.wxButtonTree.getTreeData());
//				angular.forEach($scope.wxButtonTree.getTreeData(),function(i, item) {
//
//					console.log(i + "========全部对象1======" + item);
//
//				});
            }

            WctMenuService.save($scope.wxButtonTree.getTreeData()).then(function (result) {
                if (result.success) {
                    $toast.success("操作成功！");
                } else {
                    $toast.warn(result.msg || "操作失败!");
                }
            });
        };

        //var updateMenu = function (newMenu) {
        //    // $agLoaderService.show($modalBody);
        //    WctMenuService.getWxMenu().then(function (data) {
        //        // $agLoaderService.hide($modalBody);
        //        console.log(data);
        //        $scope.wctMenu = data;
        //
        //        console.log("数据库现有菜单" + $scope.wctMenu);
        //        angular.forEach($scope.wctMenu, function (i, item) {
        //            console.log("i" + i + "=" + item);
        //        });
        //
        //        console.log("新的菜单" + newMenu);
        //
        //        angular.forEach(newMenu, function (i, item) {
        //            console.log("i" + i + "==" + item);
        //        });
        //        showDialog();
        //    })
        //};

        // 一键清空
        $scope.clearMenu = function () {
            var msg = "确认清空？";
            $dialog.confirm(msg, function (confirm) {
                if (confirm) {
                    WctMenuService.clear().then(function (result) {
                        if (result.success) {
                            $toast.success("清空成功！");
                            var wctMenu = $scope.wxButtonTree.getTreeData();
                            wctMenu.splice(0, wctMenu.length);
                        } else {
                            $toast.warn(result.msg || "清空失败！");
                        }
                    })
                }

            })
        };

        $scope.sync = function () {
            var promise = WctMenuService.sync().then(function (result) {
                if (result.success) {
                    $toast.success("同步成功!");
                    $scope.wxButtonTree.reload();
                } else {
                    $toast.error(result.msg || "同步失败!");
                }
            });
            $scope.progress.addPromise(promise);
        };
    }
})();